﻿using System.Threading;
namespace System.Web
{
    public partial class NetHttpApplication : IDisposable
    {
        private NetStepManager _stepManager;
        private WaitCallback _resumeStepsWaitCallback;

        private void ResumeStepsWaitCallback(object error) { ResumeSteps(error as Exception); }
        private void ResumeSteps(Exception error) { _stepManager.ResumeSteps(error); }
        private void ResumeStepsFromThreadPoolThread(Exception error)
        {
            if (Thread.CurrentThread.IsThreadPoolThread)
                ResumeSteps(error);
            else
                ThreadPool.QueueUserWorkItem(_resumeStepsWaitCallback, error);
        }

        internal Exception ExecuteStep(IExecutionStep step, ref bool completedSynchronously)
        {
            Exception exception = null;
            //try
            //{
            //try
            //{
            if (step.IsCancellable)
            {
                _context.WorkerRequest.BeginCancellablePeriod();
                try { step.Execute(); }
                finally { _context.WorkerRequest.EndCancellablePeriod(); }
                _context.WorkerRequest.WaitForExceptionIfCancelled();
            }
            else
                step.Execute();
            if (!step.CompletedSynchronously)
            {
                completedSynchronously = false;
                return null;
            }
            //}
            //catch (Exception ex)
            //{
            //    exception = ex;
            //    if ((ex is ThreadAbortException) && ((Thread.CurrentThread.ThreadState & ThreadState.AbortRequested) == ThreadState.Running))
            //    {
            //        exception = null;
            //        _stepManager.CompleteRequest();
            //    }
            //}
            //catch { }
            //}
            //catch (ThreadAbortException ex)
            //{
            //    if ((ex.ExceptionState != null) && (ex.ExceptionState is CancelModuleException))
            //    {
            //        var exceptionState = (CancelModuleException)ex.ExceptionState;
            //        if (exceptionState.Timeout)
            //            exception = new HttpException("Request_timed_out", null, 0xbb9);
            //        else
            //        {
            //            exception = null;
            //            _stepManager.CompleteRequest();
            //        }
            //        Thread.ResetAbort();
            //    }
            //}
            completedSynchronously = true;
            return exception;
        }
    }
}
